package com.wutao.panzh.admin.content.controller.imageUpload;


import com.panzh.UtilEntity.uplaodImag;
import com.panzh.myconst.HttpConst;
import org.csource.common.MyException;
import org.csource.fastdfs.ClientGlobal;
import org.csource.fastdfs.StorageClient;
import org.csource.fastdfs.TrackerClient;
import org.csource.fastdfs.TrackerServer;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Controller
public class WangEditor3Controller {

    @RequestMapping(value="/upload")
    @ResponseBody
    public uplaodImag imgUpload(@RequestParam("photo") List<MultipartFile> list) throws IOException, MyException {
        //上传图片到fasdfs服务器;
        List<String> datas = new ArrayList<String>();
        for (MultipartFile multipartFile : list) {
            byte[] bytes = multipartFile.getBytes();
            ClientGlobal.init("tracker.conf");
            //获取一个trackerClient，并且获得连接；
            TrackerClient trackerClient = new TrackerClient();
            TrackerServer connection = trackerClient.getConnection();

            //获取storageClient的对象；
            StorageClient storageClient = new StorageClient(connection, null);
            //上传图片到fastdfs服务器；
            String[] jpgs = storageClient.upload_file(bytes, 0, bytes.length, "jpg", null);
            String Imagepath = HttpConst.REAL_FASTDFS_HTTP_INDEX;
            for (int i = 0 ; i < jpgs.length ; i++){
                if (i == 0){
                    Imagepath += jpgs[i];
                    Imagepath += "/";
                    continue;
                }
                Imagepath += jpgs[i];
            }
            datas.add(Imagepath);
        }

        String data [] = new String[datas.size()];
        for (int i = 0 ; i < datas.size() ; i++){
            data[i] = datas.get(i);
        }
        return new uplaodImag(uplaodImag.SUCCESS,data);
    }
}
